package com.module.ble.ringMonitorService

import android.app.*
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.app.NotificationCompat
import com.module.ble.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/4/14
 *
 * 描述：监控服务基类
 *
 * 修订历史：
 *
 */
abstract class BaseMonitorService : Service() {

    override fun onCreate() {
        super.onCreate()
        // 必须显示通知（Android 9+要求）
        startForeground(getNotificationId(), buildNotification())

        // 初始化监听
        initListener()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY // 如果服务被系统杀死后自动重启
    }

    override fun onBind(intent: Intent?) = null

    override fun onDestroy() {
        // 清理资源
        cleanupListener()
        super.onDestroy()
    }

    // 通知构建（适配Android 13+）
    private fun buildNotification(): Notification {
        // 创建独立通知渠道（Android 8+）
        createNotificationChannel()

        // 使用 Scheme URI 创建 Intent
        val schemeUri = Uri.parse("rsopen://ring.blackshark.com/main")
        val mainIntent = Intent(Intent.ACTION_VIEW, schemeUri).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
        }

        val pendingIntent = PendingIntent.getActivity(
            this, 0,
            mainIntent,
            PendingIntent.FLAG_IMMUTABLE
        )

        return NotificationCompat.Builder(this, getChannelId())
            .setContentTitle(getNotificationTitle())
            .setSmallIcon(R.mipmap.ic_logo_launcher_round)
            .setCategory(Notification.CATEGORY_SERVICE)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setPriority(NotificationCompat.PRIORITY_LOW) // 降低通知优先级
            .setContentIntent(pendingIntent)
            .build()
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                getChannelId(),
                getChannelName(),
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = getChannelDescription()
                lockscreenVisibility = Notification.VISIBILITY_PUBLIC
            }

            getSystemService(NotificationManager::class.java)
                ?.createNotificationChannel(channel)
        }
    }

    // 抽象方法 - 由子类实现
    protected abstract fun getNotificationId(): Int
    protected abstract fun getChannelId(): String
    protected abstract fun getChannelName(): String
    protected abstract fun getChannelDescription(): String
    protected abstract fun getNotificationTitle(): String
    protected abstract fun initListener()
    protected abstract fun cleanupListener()
}